Perl Operators

您所在的位置:网站首页 kayboard operator Perl Operators

Perl Operators

2024-07-09 12:15| 来源: 网络整理| 查看: 265

Summary: in this tutorial, you’ll learn about Perl operators including numeric operators, string operators, and logical operators.

Perl OperatorsNumeric operators

Perl provides numeric operators to help you operate on numbers including arithmetic, Boolean and bitwise operations. Let’s examine the different kinds of operators in more detail.

Arithmetic operators

Perl arithmetic operators deal with basic math such as adding, subtracting, multiplying, diving, etc. To add (+ ) or subtract (-) numbers, you would do something as follows:

#!/usr/bin/perl use warnings; use strict; print 10 + 20, "\n"; # 30 print 20 - 10, "\n"; # 10Code language: Perl (perl)

To multiply or divide numbers, you use divide (/) and multiply (*) operators as follows:

#!/usr/bin/perl use warnings; use strict; print 10 * 20, "\n"; # 200 print 20 / 10, "\n"; # 2Code language: PHP (php)

When you combine adding, subtracting, multiplying, and dividing operators together, Perl will perform the calculation in an order, which is known as operator precedence.

The multiply and divide operators have higher precedence than add and subtract operators, therefore, Perl performs multiplying and dividing before adding and subtracting. See the following example:

print 10 + 20/2 - 5 * 2 , "\n"; # 10Code language: Perl (perl)

Perl performs 20/2 and 5*2 first, therefore you will get 10 + 10 – 10 = 10.

You can use brackets () to force Perl to perform calculations based on the precedence you want as shown in the following example:

print (((10 + 20)/2 - 5) * 2); # 20;Code language: Perl (perl)

To raise one number to the power of another number, you use the exponentiation operator (**) e.g., 2**3 = 2 * 2 * 2. The following example demonstrates the exponentiation operators:

#!/usr/bin/perl use warnings; use strict; print 2**3, "\n"; # = 2 * 2 * 2 = 8. print 3**4, "\n"; # = 3 * 3 * 3 * 3 = 81.Code language: Perl (perl)

To get the remainder of the division of one number by another, you use the modulo operator (%).

It is handy to use the modulo operator (%) to check if a number is odd or even by dividing it by 2 to get the remainder. If the remainder is zero, the number is even, otherwise, the number is odd. See the following example:

#!/usr/bin/perl use warnings; use strict; print 4 % 2, "\n"; # 0 even print 5 % 2, "\n"; # 1 oddCode language: Perl (perl)Bitwise Operators

Bitwise operators allow you to operate on numbers one bit at a time. Think of a number as a series of bits e.g., 125 can be represented in binary form as 1111101. Perl provides all basic bitwise operators including and (&), or (|), exclusive or (^) , not (~) operators, shift right (>>), and shift left ( 1; # 0101 shift right 1 bit, 010 or 2 print $c, "\n"; $c = $a



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3